package com.finger.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.finger.commonutils.R;
import com.finger.eduservice.entity.EduChapter;
import com.finger.eduservice.entity.EduVideo;
import com.finger.eduservice.entity.vo.ChapterVO;
import com.finger.eduservice.entity.vo.VideoVO;
import com.finger.eduservice.mapper.EduChapterMapper;
import com.finger.eduservice.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.finger.eduservice.service.EduVideoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-01-06
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Autowired
    private EduVideoService eduVideoService;


    @Override
    public List<ChapterVO> getAllChapter(String courseId) {

        QueryWrapper<EduChapter> chapterQueryWrapper = new QueryWrapper<>();

        chapterQueryWrapper.eq("course_id",courseId);

        chapterQueryWrapper.orderByAsc("sort");
        // 章节集合
        List<EduChapter> eduChapterList = baseMapper.selectList(chapterQueryWrapper);

        QueryWrapper<EduVideo> videoQueryWrapper = new QueryWrapper<>();

        videoQueryWrapper.eq("course_id",courseId);
        // 小节集合
        List<EduVideo> eduVideoList = eduVideoService.list(videoQueryWrapper);

        List<ChapterVO> finalList = new ArrayList<>();

        for (EduChapter eduChapter : eduChapterList) {

            ChapterVO chapterVO = new ChapterVO();

            BeanUtils.copyProperties(eduChapter,chapterVO);

            for (EduVideo eduVideo : eduVideoList) {

                if(Objects.equals(eduChapter.getId(),eduVideo.getChapterId())){

                    VideoVO videoVO = new VideoVO();

                    BeanUtils.copyProperties(eduVideo,videoVO);

                    chapterVO.getChildren().add(videoVO);
                }
            }

            finalList.add(chapterVO);
        }
        return finalList;
    }


    @Override
    public R removeChapterById(String chapterId) {

        QueryWrapper<EduVideo> eduVideoQueryWrapper = new QueryWrapper<>();

        eduVideoQueryWrapper.eq("chapter_id",chapterId);

        int count = eduVideoService.count(eduVideoQueryWrapper);

        if(count>0){
            return R.error();
        }

        baseMapper.deleteById(chapterId);

        return R.ok();
    }
}
